<template>
  <div>
    <h2 class="mb-4">OCR识别配置</h2>
    <a-form :model="form" layout="vertical">
      <a-form-item label="OCR服务商" name="provider">
        <a-select v-model:value="form.provider" placeholder="请选择OCR服务商">
          <a-select-option value="aliyun">阿里云OCR</a-select-option>
          <a-select-option value="mock">模拟OCR</a-select-option>
        </a-select>
      </a-form-item>

      <template v-if="form.provider === 'aliyun'">
        <a-form-item label="AccessKey ID" name="accessKeyId">
          <a-input v-model:value="form.accessKeyId" placeholder="请输入AccessKey ID" />
        </a-form-item>
        <a-form-item label="AccessKey Secret" name="accessKeySecret">
          <a-input-password v-model:value="form.accessKeySecret" placeholder="请输入AccessKey Secret" />
        </a-form-item>
        <a-form-item label="Endpoint" name="endpoint">
          <a-input v-model:value="form.endpoint" placeholder="请输入Endpoint" />
        </a-form-item>
        <a-form-item label="Region ID" name="regionId">
          <a-input v-model:value="form.regionId" placeholder="请输入Region ID" />
        </a-form-item>
      </template>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSave">保存配置</a-button>
          <a-button @click="handleTest">测试连接</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 测试区域 -->
    <div class="test-area">
      <a-collapse v-model:activeKey="activeKey" :bordered="false">
        <a-collapse-panel key="1" :show-arrow="false">
          <template #header>
            <div class="collapse-header">
              <h2 class="mb-0">OCR测试</h2>
              <a-button type="link" @click.stop="toggleTest">
                {{ isExpanded ? '收起' : '展开' }}
                <down-outlined :class="{ 'rotate-icon': isExpanded }" />
              </a-button>
            </div>
          </template>

          <!-- OCR类型选择 -->
          <div class="ocr-type-select mb-4">
            <a-form-item label="OCR类型" name="ocrType">
              <a-select v-model:value="selectedOcrType" placeholder="请选择OCR类型">
                <a-select-option value="">通用识别</a-select-option>
                <a-select-option value="general">通用文字识别</a-select-option>
                <a-select-option value="idCard">身份证识别</a-select-option>
                <a-select-option value="bankCard">银行卡识别</a-select-option>
                <a-select-option value="businessLicense">营业执照识别</a-select-option>
              </a-select>
            </a-form-item>
          </div>

          <!-- 图片上传区域 -->
          <div class="upload-section">
            <a-upload
              v-model:file-list="fileList"
              :before-upload="beforeUpload"
              :customRequest="handleUpload"
              :show-upload-list="false"
              accept="image/*"
            >
              <div class="upload-box">
                <upload-outlined />
                <div class="mt-2">点击或拖拽图片到此处</div>
                <div class="upload-tip">支持 jpg、png、jpeg 格式，单个文件不超过5MB</div>
              </div>
            </a-upload>
          </div>

          <!-- 识别结果 -->
          <div v-if="recognitionResult" class="result-section mt-4">
            <h3 class="mb-4">识别结果</h3>
            <div class="result-content">
              <div class="image-preview">
                <img :src="recognitionResult.imageUrl" alt="预览图" />
              </div>
              <div class="result-details">
                <a-descriptions bordered size="small">
                  <a-descriptions-item v-for="(value, key) in recognitionResult.details" :key="key" :label="key">
                    {{ value }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
          </div>

          <!-- 识别历史 -->
          <div class="history-section mt-4">
            <h3 class="mb-4">识别历史</h3>
            <a-table
              :columns="columns"
              :data-source="recognitionHistory"
              :pagination="{ pageSize: 5 }"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="record.status === 'success' ? 'success' : 'error'">
                    {{ record.status === 'success' ? '识别成功' : '识别失败' }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" size="small" @click="handleViewHistory(record)">
                    查看详情
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, DownOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import type { UploadFile } from 'ant-design-vue/es/upload/interface'
import axios from 'axios'

const form = reactive({
  provider: 'aliyun',
  accessKeyId: '',
  accessKeySecret: '',
  endpoint: '',
  regionId: ''
})

// 选中的OCR类型
const selectedOcrType = ref('')

// 文件列表
const fileList = ref<UploadFile[]>([])

// 识别结果
interface RecognitionResult {
  imageUrl: string
  details: Record<string, string>
}

const recognitionResult = ref<RecognitionResult | null>(null)

// 识别历史
interface RecognitionRecord {
  id: number
  fileName: string
  type: string
  status: 'success' | 'error'
  time: string
  result?: RecognitionResult
}

const recognitionHistory = ref<RecognitionRecord[]>([])

// 表格列定义
const columns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
  },
  {
    title: '识别类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 检查是否是首次配置
const isFirstConfig = ref(true)

// 检查OCR配置是否已填写
const isOcrConfigured = () => {
  if (form.provider === 'aliyun') {
    return !!(form.accessKeyId && form.accessKeySecret && form.endpoint && form.regionId)
  }
  return form.provider === 'mock'
}

// 加载配置
const loadConfig = async () => {
  try {
    const response = await axios.get('/api/ocr/config')
    if (response.data) {
      const config = response.data
      form.provider = config.type || 'aliyun'
      
      if (config.type === 'aliyun') {
        form.accessKeyId = config.accessKeyId || ''
        form.accessKeySecret = config.accessKeySecret || ''
        form.endpoint = config.endpoint || ''
        form.regionId = config.regionId || ''
      } else {
        resetForm()
      }
      isFirstConfig.value = false
    }
  } catch (error: any) {
    if (isFirstConfig.value) {
      resetForm()
      return
    }
    console.error('加载配置失败：', error)
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('加载配置失败，请稍后重试')
    }
  }
}

// 重置表单
const resetForm = () => {
  form.provider = 'aliyun'
  form.accessKeyId = ''
  form.accessKeySecret = ''
  form.endpoint = ''
  form.regionId = ''
}

// 保存配置
const handleSave = async () => {
  try {
    if (form.provider === 'aliyun') {
      if (!form.accessKeyId || !form.accessKeySecret || !form.endpoint || !form.regionId) {
        message.warning('请填写完整的OCR配置信息')
        return
      }
    }

    const config = {
      type: form.provider,
      accessKeyId: form.accessKeyId,
      accessKeySecret: form.accessKeySecret,
      endpoint: form.endpoint,
      regionId: form.regionId
    }
    
    const response = await axios.post('/api/ocr/switch', config)
    if (response.data) {
      message.success('OCR配置保存成功')
      isFirstConfig.value = false
      await loadConfig()
    }
  } catch (error: any) {
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('保存配置失败，请稍后重试')
    }
  }
}

// 测试连接
const handleTest = async () => {
  try {
    if (form.provider === 'aliyun') {
      if (!form.accessKeyId || !form.accessKeySecret || !form.endpoint || !form.regionId) {
        message.warning('请填写完整的OCR配置信息')
        return
      }
    }

    const config = {
      type: form.provider,
      accessKeyId: form.accessKeyId,
      accessKeySecret: form.accessKeySecret,
      endpoint: form.endpoint,
      regionId: form.regionId
    }
    
    const response = await axios.post('/api/ocr/switch', config)
    if (response.data) {
      message.success('OCR服务连接测试成功')
    }
  } catch (error: any) {
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('测试连接失败，请稍后重试')
    }
  }
}

// 组件挂载时加载配置
onMounted(async () => {
  await loadConfig()
})

// 上传前检查
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 处理文件上传
const handleUpload: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
  try {
    if (!isOcrConfigured()) {
      message.warning('请先完成OCR服务配置')
      onError?.(new Error('OCR服务未配置'))
      return
    }

    if (!file) {
      message.error('图片上传失败：文件对象为空')
      onError?.(new Error('文件对象为空'))
      return
    }

    const uploadFile = file as UploadFile
    const originFile = uploadFile.originFileObj || file

    if (!originFile || !(originFile instanceof File)) {
      message.error('图片上传失败：无法获取有效的文件对象')
      onError?.(new Error('无法获取有效的文件对象'))
      return
    }

    const fileType = originFile.type
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg']
    if (!allowedTypes.includes(fileType)) {
      message.error('图片上传失败：只支持 JPG、PNG 格式的图片')
      onError?.(new Error('不支持的文件类型'))
      return
    }

    const maxSize = 5 * 1024 * 1024
    if (originFile.size > maxSize) {
      message.error('图片上传失败：文件大小不能超过5MB')
      onError?.(new Error('文件大小超出限制'))
      return
    }

    const formData = new FormData()
    formData.append('file', originFile)
    formData.append('serviceType', selectedOcrType.value)

    const response = await axios.post('/api/ocr/recognize', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000,
      validateStatus: null
    })

    if (response.status !== 200) {
      throw new Error(`OCR识别失败：服务器返回错误状态码 ${response.status}, ${response.statusText}`)
    }

    if (!response.data) {
      throw new Error('OCR识别失败：服务器返回数据为空')
    }

    const result: RecognitionResult = {
      imageUrl: URL.createObjectURL(originFile),
      details: response.data
    }
    recognitionResult.value = result

    const record: RecognitionRecord = {
      id: Date.now(),
      fileName: originFile.name || '未命名文件',
      type: selectedOcrType.value,
      status: 'success',
      time: new Date().toLocaleString(),
      result
    }
    recognitionHistory.value.unshift(record)

    onSuccess?.('ok')
    message.success('识别成功')
  } catch (error: any) {
    console.error('OCR处理失败:', error)
    
    onError?.(error as Error)
    if (error.message.includes('图片上传失败')) {
      message.error(error.message)
    } else if (error.response?.data?.message) {
      message.error(`OCR识别失败：${error.response.data.message}`)
    } else if (error.message.includes('OCR识别失败')) {
      message.error(error.message)
    } else {
      message.error('OCR识别失败，请稍后重试')
    }
  }
}

// 查看历史记录
const handleViewHistory = (record: RecognitionRecord) => {
  if (record.result) {
    recognitionResult.value = record.result
  }
}

// 折叠面板状态
const activeKey = ref<string[]>([])
const isExpanded = ref(false)

// 切换测试区域显示状态
const toggleTest = () => {
  isExpanded.value = !isExpanded.value
  activeKey.value = isExpanded.value ? ['1'] : []
}
</script>

<style scoped>
.test-area {
  margin-top: 24px;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.upload-section {
  margin-top: 16px;
}

.upload-box {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 32px;
  text-align: center;
  background: #fafafa;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-box:hover {
  border-color: #1890ff;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.result-section {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
}

.result-content {
  display: flex;
  gap: 16px;
}

.image-preview {
  flex: 0 0 300px;
}

.image-preview img {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

.result-details {
  flex: 1;
}

.history-section {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
}

.rotate-icon {
  transform: rotate(180deg);
}

.ocr-type-select {
  margin-bottom: 16px;
}
</style>